//
//  WowDaraFirstViewController.m
//  WowDara
//
//  Created by Siroj Chongkolwanont on 3/30/56 BE.
//  Copyright (c) 2556 Siroj Chongkolwanont. All rights reserved.
//

#import "WowDaraFirstViewController.h"
#import "News.h"
#import "NewsFeed.h"
#import "NewsFeedContent.h"
#import  "WowDaraNewsContent.h"

@interface WowDaraFirstViewController ()

@end

@implementation WowDaraFirstViewController


@synthesize hilightButton;
@synthesize hilightBtn;
@synthesize wowBtn;
@synthesize newsTable;


NSMutableArray *hilightArray;
NSMutableArray *feedArray;
UIActivityIndicatorView *spinner;
NSString* news_id;
UIRefreshControl *refreshControl;


NewsFeed *currentFeed;

id jsonObjectFromUrlString(NSString *urlString);


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger row = [hilightArray count];
    
    return row;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  {
    NSInteger row = indexPath.row;
    
  
    
    
    News* hilight = [hilightArray objectAtIndex:row];
    currentFeed = [feedArray objectAtIndex:row];
    news_id = hilight.id;
    
    NSString *url_picture = @"http://119.59.127.95/~wowdara/";
    
    url_picture = [url_picture stringByAppendingString:hilight.image];
    
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url_picture]];
    
    [hilightButton setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
    
  

}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"NewsCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    NSInteger row = indexPath.row;
    
    //News* hilight = hilightArray[row];
    NewsFeed* feed = feedArray[row];
    
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    // Here we use the new provided setImageWithURL: method to load the web image
    
    NSString *url_picture = @"http://119.59.127.95/~wowdara/";
    
    url_picture = [url_picture stringByAppendingString:feed.image];
    
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url_picture]];
    
    
    // Display recipe in the table cell
    //Recipe *recipe = [recipes objectAtIndex:indexPath.row];
    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
    
    recipeImageView.image = [UIImage imageWithData:imageData];
    
    UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:101];
    recipeNameLabel.text = feed.name;
    
    
    UILabel *subdescLabel = (UILabel *)[cell viewWithTag:102];
    subdescLabel.text = feed.sub_description;
    
    //cell.textLabel.text = hilight.name;
    
    return cell;
}


- (void)load_news:(NSInteger)option
{
    hilightArray = [[NSMutableArray alloc] init];
    feedArray  = [[NSMutableArray alloc] init];
    
    NSString *banner_str = [NSString stringWithFormat:@"http://119.59.127.95/~wowdara/android/getNewsBanner.php?type=%d", option];
    
    NSString *feed_str = [NSString stringWithFormat:@"http://119.59.127.95/~wowdara/android/getNewsFeed.php?type=%d", option];
    
    
    NSDictionary *publicBanner =  jsonObjectFromUrlString(banner_str);
    
    
    NSDictionary *publicFeed =  jsonObjectFromUrlString(feed_str);
    
    
    
    for(NSString *item in [publicBanner allKeys]) {
        
        if([item isEqual: @"news"] )
        {
            NSArray *allBanner = [publicBanner valueForKey:item];
            
            for(NSDictionary *hilight in allBanner )
            {
                News* hilight_obj = [[News alloc] init];
                hilight_obj.id = [hilight valueForKey:@"id"];
                hilight_obj.name = [hilight valueForKey:@"name"];
                hilight_obj.image = [hilight valueForKey:@"image"];
                hilight_obj.image_inside_tmp  = [hilight valueForKey:@"image_inside_tmp"];
                [hilightArray addObject:hilight_obj];
            }
            
        }
    }
    
    
    for(NSString *item in [publicFeed allKeys]) {
        
        if([item isEqual: @"news"] )
        {
            NSArray *allBanner = [publicFeed valueForKey:item];
            
            for(NSDictionary *hilight in allBanner )
            {
                NewsFeed* feed_obj = [[NewsFeed alloc] init];
                feed_obj.id = [hilight valueForKey:@"id"];
                feed_obj.name = [hilight valueForKey:@"name"];
                feed_obj.image = [hilight valueForKey:@"image"];
                feed_obj.sub_description = [hilight valueForKey:@"sub_description"];
                [feedArray addObject:feed_obj];
            }
            
        }
    }
    

    News* hilight = [hilightArray objectAtIndex:0];
    
    NSString *url_picture = @"http://119.59.127.95/~wowdara/";
    
    url_picture = [url_picture stringByAppendingString:hilight.image];
    
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url_picture]];
    
    [hilightButton setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
    
    [newsTable reloadData];
    
    news_id = hilight.id;
    
    currentFeed = [feedArray objectAtIndex:0];
    
    
}


- (void)viewDidLoad
{
    
    
    spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    spinner.center = CGPointMake(160, 140);
    spinner.hidesWhenStopped = YES;
    [self.view addSubview:spinner];
    
    

    


    //[spinner startAnimating];
    
    UIImage *selectedImage0 = [UIImage imageNamed:@"tab_news_active.png"];
    UIImage *unselectedImage0 = [UIImage imageNamed:@"tab_news.png"];
    
    UIImage *selectedImage1 = [UIImage imageNamed:@"tab_dara_active.png"];
    UIImage *unselectedImage1 = [UIImage imageNamed:@"tab_dara.png"];
    
    UIImage *selectedImage2 = [UIImage imageNamed:@"tab_video_active.png"];
    UIImage *unselectedImage2 = [UIImage imageNamed:@"tab_video.png"];
    
    UIImage *selectedImage3 = [UIImage imageNamed:@"tab_gallery_active.png"];
    UIImage *unselectedImage3 = [UIImage imageNamed:@"tab_gallery.png"];
    
    CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 49);
    UIView *v = [[UIView alloc] initWithFrame:frame];
    
    UIButton *button1 = [[UIButton alloc] init];
    button1.frame= CGRectMake(0,0,43,32);
    [button1 setBackgroundImage:[UIImage imageNamed: @"nav_contact.png"] forState:UIControlStateNormal];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
    
    
    
    [v setBackgroundColor:[UIColor whiteColor]];
    
    UITabBar *tabBar = self.tabBarController.tabBar;
    UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
    UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
    UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
    UITabBarItem *item3 = [tabBar.items objectAtIndex:3];
    
    [item0 setFinishedSelectedImage:selectedImage0 withFinishedUnselectedImage:unselectedImage0];
    [item1 setFinishedSelectedImage:selectedImage1 withFinishedUnselectedImage:unselectedImage1];
    [item2 setFinishedSelectedImage:selectedImage2 withFinishedUnselectedImage:unselectedImage2];
    [item3 setFinishedSelectedImage:selectedImage3 withFinishedUnselectedImage:unselectedImage3];
    
    
    self.navigationController.navigationBar.tintColor = [UIColor redColor];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"nav_bg.png"]
                   forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController.navigationBar.topItem setTitleView:[[UIImageView alloc] initWithImage:[UIImage  imageNamed:@"toolbar_logo.png"]]];
    
    
    
    
    
    [super viewDidLoad];
    
    [spinner startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                   {
                       //do something expensive
                       [self load_news:1];
                       
                       //dispatch back to the main (UI) thread to stop the activity indicator
                       dispatch_async(dispatch_get_main_queue(), ^
                                      {
                                          News* hilight = [hilightArray objectAtIndex:0];
                                          
                                          NSString *url_picture = @"http://119.59.127.95/~wowdara/";
                                          
                                          url_picture = [url_picture stringByAppendingString:hilight.image];
                                          
                                          NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url_picture]];
                                          
                                          [hilightButton setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
                                          
                                          [newsTable reloadData];
                                          
                                          news_id = hilight.id;
                                          
                                          currentFeed = [feedArray objectAtIndex:0];
                                          
                                          [spinner stopAnimating];
                                      });
                   });
    
    
    //[self load_news:1];

    //[hilightButton setImage:[UIImage imageWithData:imageData] forState: UIControlStateApplication];
	// Do any additional setup after loading the view, typically from a nib.
    
    //[spinner stopAnimating];
    

    refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refresh)
             forControlEvents:UIControlEventValueChanged];
    // = refreshControl;
    
    
     [newsTable addSubview:refreshControl];
    
}

-(void)refresh {
    
    [UIView animateWithDuration:2 delay:1 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
        
        [spinner startAnimating];
        [self load_news:1];
        
    } completion:^(BOOL finished){
        [spinner stopAnimating];
        [refreshControl endRefreshing];
    }];
    

    
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)hilightBtn_click:(id)sender {
    
    [hilightBtn setBackgroundImage:[UIImage imageNamed:@"sc_1active.png"] forState:UIControlStateNormal];
    [wowBtn setBackgroundImage:[UIImage imageNamed:@"sc_2.png"] forState:UIControlStateNormal];
    
    
    [self load_news:1];
    
    [spinner stopAnimating];
}

- (IBAction)wowBtn_click:(id)sender {
    [hilightBtn setBackgroundImage:[UIImage imageNamed:@"sc_1.png"] forState:UIControlStateNormal];
    [wowBtn setBackgroundImage:[UIImage imageNamed:@"sc_2active.png"] forState:UIControlStateNormal];
    
    [spinner startAnimating];
    
    [self load_news:2];
    
    [spinner stopAnimating];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    
    //if([segue.identifier isEqualToString:@"ToSummary"])
    {
        WowDaraNewsContent *p = (WowDaraNewsContent*)segue.destinationViewController;
        p.news_id = news_id;
        p.feed = currentFeed;        
    }
    
}
@end
